# -*- coding:utf-8 -*-
import pywencai
import math

from infrastructure.utils.dateUtil import getTodayyyyymmddInt
from infrastructure.utils.dbUtil import SqliteUtil, SqliteConfig
from config.baseConfiguration import Sqlite3Config
from infrastructure.utils.log import logger

config = SqliteConfig(dbPath=Sqlite3Config.dbPath)


def getStockCodes(ss, stocks):
    cs = []
    for s in ss:
        s = s.strip()
        if s in stocks:
            cs.append(stocks[s])
        else:
            cs.append(stocks[f"ST{s[0:2]}"])
    return ",".join(cs)


def updateRatios(dti):
    db = SqliteUtil.get_instance(dbConfig=config)
    sql = ("select dti, hps, lps, shcje, szcje, cycje, kccje, bjcje, zts, zbs, lbs, lbs2, lbs3, lbs4p, "
           "zlbzs, zlbds, zlbdzs, zlbdds, z2lbzs, z2lbds, z2lbdzs, z2lbdds, z3lbzs, z3lbds, z3lbdzs, z3lbdds, "
           "z4plbzs, z4plbds, z4plbdzs, z4plbdds, z4plbfstbx, z3lbfstbx, z2lbfstbx, "
           "zztzs, zztds, zztdzs, zztdds,"
           "zsbzs, zsbds, zsbdzs, zsbdds, "
           "zsboc5ds, zlboc5ds "
           "from market_sentiment")
    if dti > 0:
        sql += f" where dti = {dti}"
    market_sentiments = db.get_all(sql)
    for market_sentiment in market_sentiments:
        dti = market_sentiment[0]
        hps = market_sentiment[1]
        lps = market_sentiment[2]

        shcje = market_sentiment[3]
        szcje = market_sentiment[4]
        cycje = market_sentiment[5]
        kccje = market_sentiment[6]
        bjcje = market_sentiment[7]

        zts = market_sentiment[8]
        zbs = market_sentiment[9]

        lbs = market_sentiment[10]
        lbs2 = market_sentiment[11]
        lbs3 = market_sentiment[12]
        lbs4p = market_sentiment[13]

        zlbzs = market_sentiment[14]
        zlbds = market_sentiment[15]
        zlbdzs = market_sentiment[16]
        zlbdds = market_sentiment[17]

        z2lbzs = market_sentiment[18]
        z2lbds = market_sentiment[19]
        z2lbdzs = market_sentiment[20]
        z2lbdds = market_sentiment[21]

        z3lbzs = market_sentiment[22]
        z3lbds = market_sentiment[23]
        z3lbdzs = market_sentiment[24]
        z3lbdds = market_sentiment[25]

        z4plbzs = market_sentiment[26]
        z4plbds = market_sentiment[27]
        z4plbdzs = market_sentiment[28]
        z4plbdds = market_sentiment[29]

        z4plbfstbx = market_sentiment[30]
        z3lbfstbx = market_sentiment[31]
        z2lbfstbx = market_sentiment[32]

        zztzs = market_sentiment[33]
        zztds = market_sentiment[34]
        zztdzs = market_sentiment[35]
        zztdds = market_sentiment[36]

        zsbzs = market_sentiment[37]
        zsbds = market_sentiment[38]
        zsbdzs = market_sentiment[39]
        zsbdds = market_sentiment[40]

        zsboc5ds = market_sentiment[41]
        zlboc5ds = market_sentiment[42]

        sql = f"""
            select dti, lbs, lbs2, lbs3, lbs4p, z4plbfstbx, fbl, bl2j3, bldjd, z3lbfstbx, z2lbfstbx, zts 
            from market_sentiment 
            where dti < {dti} order by dti desc limit 1
            """
        ymarket_sentiment = db.get_one(sql)
        zdti = ymarket_sentiment[0]
        zlbs = ymarket_sentiment[1]
        zlbs2 = ymarket_sentiment[2]
        zlbs3 = ymarket_sentiment[3]
        zlbs4p = ymarket_sentiment[4]
        zz4plbfstbx = ymarket_sentiment[5]
        zfbl = ymarket_sentiment[6]
        zbl2j3 = ymarket_sentiment[7]
        zbldjd = ymarket_sentiment[8]
        zz3lbfstbx = ymarket_sentiment[9]
        zz2lbfstbx = ymarket_sentiment[10]
        zzts = ymarket_sentiment[11]
        zsbs = zzts - zlbs

        hlzs = hps + lps # 红盘绿盘总数
        hpbl = round(1.0 * hps/hlzs * 100, 2) if hlzs > 0 else 0
        zcje = round(shcje + szcje + cycje + kccje + bjcje, 2) # 总成交额
        fbl = round(1.0 * zts/(zts + zbs) * 100, 2) if zts + zbs > 0 else 0 # 封板率
        lbbz = round(lbs/zlbs, 2) # 连扳比值
        bl2j3 = round(1.0 * lbs3/zlbs2 * 100, 2) if zlbs2 > 0 else 0 # 2进3比率
        bldjd = round(1.0 * lbs4p/(zlbs3 + zlbs4p) * 100, 2) if zlbs3 + zlbs4p > 0 else 0 # 多进多比率

        zztzbl = round(1.0 * zztzs / zzts * 100, 2) if zzts > 0 else 0 # 昨日涨停今日涨比
        zztdbl = round(1.0 * zztds / zzts * 100, 2) if zzts > 0 else 0 # 昨日涨停今日跌比
        zztdzbl = round(1.0 * zztdzs / zzts * 100, 2) if zzts > 0 else 0 # 昨日涨停今日大涨比
        zztddbl = round(1.0 * zztdds / zzts * 100, 2) if zzts > 0 else 0 # 昨日涨停今日大跌比

        zsbzbl = round(1.0 * zsbzs / zsbs * 100, 2) if zsbs > 0 else 0 # 昨日首板今日涨比
        zsbdbl = round(1.0 * zsbds / zsbs * 100, 2) if zsbs > 0 else 0 # 昨日首板今日跌比
        zsbdzbl = round(1.0 * zsbdzs / zsbs * 100, 2) if zsbs > 0 else 0 # 昨日首板今日大涨比
        zsbddbl = round(1.0 * (zsbdds + zsboc5ds) / zsbs * 100, 2) if zsbs > 0 else 0 # 昨日首板今日大跌比

        zlbzbl = round(1.0 * zlbzs / zlbs * 100, 2) if zlbs > 0 else 0 # 昨日连扳今日涨比
        zlbdbl = round(1.0 * zlbds / zlbs * 100, 2) if zlbs > 0 else 0 # 昨日连扳今日跌比
        zlbdzbl = round(1.0 * zlbdzs / zlbs * 100, 2) if zlbs > 0 else 0 # 昨日连扳今日大涨比
        zlbddbl = round(1.0 * (zlbdds + zlboc5ds) / zlbs * 100, 2) if zlbs > 0 else 0 # 昨日连扳今日大跌比

        z2lbzbl = round(1.0 * z2lbzs / zlbs2 * 100, 2) if zlbs2 > 0 else 0 # 昨日2连扳今日涨比
        z2lbdbl = round(1.0 * z2lbds / zlbs2 * 100, 2) if zlbs2 > 0 else 0 # 昨日2连扳今日涨比
        z2lbdzbl = round(1.0 * z2lbdzs / zlbs2 * 100, 2) if zlbs2 > 0 else 0 # 昨日2连扳今日涨比
        z2lbddbl = round(1.0 * z2lbdds / zlbs2 * 100, 2) if zlbs2 > 0 else 0 # 昨日2连扳今日涨比

        z3lbzbl = round(1.0 * z3lbzs / zlbs3 * 100, 2) if zlbs3 > 0 else 0 # 昨日3连扳今日涨比
        z3lbdbl = round(1.0 * z3lbds / zlbs3 * 100, 2) if zlbs3 > 0 else 0 # 昨日3连扳今日涨比
        z3lbdzbl = round(1.0 * z3lbdzs / zlbs3 * 100, 2) if zlbs3 > 0 else 0 # 昨日3连扳今日涨比
        z3lbddbl = round(1.0 * z3lbdds / zlbs3 * 100, 2) if zlbs3 > 0 else 0 # 昨日3连扳今日涨比

        z4plbzbl = round(1.0 * z4plbzs / zlbs4p * 100, 2) if zlbs4p > 0 else 0 # 昨日4板及以上连扳今日涨比
        z4plbdbl = round(1.0 * z4plbds / zlbs4p * 100, 2) if zlbs4p > 0 else 0 # 昨日4板及以上连扳今日涨比
        z4plbdzbl = round(1.0 * z4plbdzs / zlbs4p * 100, 2) if zlbs4p > 0 else 0 # 昨日4板及以上连扳今日涨比
        z4plbddbl = round(1.0 * z4plbdds / zlbs4p * 100, 2) if zlbs4p > 0 else 0 # 昨日4板及以上连扳今日涨比
        tjqx = 0
        bk = False
        if tjqx == 0 and not bk:
            if bldjd > zbldjd:
                tjqx = 1
            elif bldjd < zbldjd:
                bk = True
        if tjqx == 0 and not bk:
            if bl2j3 > zbl2j3:
                tjqx = 1
            elif bl2j3 < zbl2j3:
                bk = True
        if tjqx == 0 and not bk:
            if fbl > zfbl:
                tjqx = 1
            elif fbl < zfbl:
                bk = True
        if tjqx == 0 and not bk:
            if z4plbfstbx > zz4plbfstbx:
                tjqx = 1
            elif z4plbfstbx < zz4plbfstbx:
                bk = True
        if tjqx == 0 and not bk:
            if z4plbfstbx > zz4plbfstbx:
                tjqx = 1
            elif z4plbfstbx < zz4plbfstbx:
                bk = True
        if tjqx == 0 and not bk:
            if z3lbfstbx > zz3lbfstbx:
                tjqx = 1
            elif z3lbfstbx < zz3lbfstbx:
                bk = True
        if tjqx == 0 and not bk:
            if z2lbfstbx > zz2lbfstbx:
                tjqx = 1
            elif z2lbfstbx < zz2lbfstbx:
                bk = True

        fbcjesql = f"select dti, code, count, cje, type  from stock_board where dti={dti}"
        fbs = db.get_all(fbcjesql)
        ztcje = 0
        dtcje = 0
        lbcje = 0
        lb2cje = 0
        lb3cje = 0
        lb4pcje = 0
        if fbs is not None or len(fbs) > 0:
            for fb in fbs:
                count = fb[2]
                cje = fb[3]
                type = fb[4]
                if type == 0:
                    dtcje = dtcje + cje
                elif count == 1:
                    ztcje = ztcje + cje
                elif count == 2:
                    ztcje = ztcje + cje
                    lbcje = lbcje + cje
                    lb2cje = lb2cje + cje
                elif count == 3:
                    ztcje = ztcje + cje
                    lbcje = lbcje + cje
                    lb3cje = lb3cje + cje
                else:
                    ztcje = ztcje + cje
                    lbcje = lbcje + cje
                    lb4pcje = lb4pcje + cje


        usql = f"""
            update market_sentiment set 
                hlzs={hlzs}, zcje={zcje}, fbl={fbl}, bl2j3={bl2j3}, bldjd={bldjd}, tjqx={tjqx},
                 zlbzbl={zlbzbl}, zlbdbl={zlbdbl}, zlbdzbl={zlbdzbl}, zlbddbl={zlbddbl}, 
                 z2lbzbl={z2lbzbl}, z2lbdbl={z2lbdbl}, z2lbdzbl={z2lbdzbl}, z2lbddbl={z2lbddbl}, 
                 z3lbzbl={z3lbzbl}, z3lbdbl={z3lbdbl}, z3lbdzbl={z3lbdzbl}, z3lbddbl={z3lbddbl}, 
                 z4plbzbl={z4plbzbl}, z4plbdbl={z4plbdbl}, z4plbdzbl={z4plbdzbl}, z4plbddbl={z4plbddbl},
                 ztcje={ztcje}, dtcje={dtcje}, lbcje={lbcje}, lb2cje={lb2cje}, lb3cje={lb3cje}, lb4pcje={lb4pcje},
                 zztzbl={zztzbl}, zztdbl={zztdbl}, zztdzbl={zztdzbl}, zztddbl={zztddbl},
                 zsbzbl={zsbzbl}, zsbdbl={zsbdbl}, zsbdzbl={zsbdzbl}, zsbddbl={zsbddbl},
                 lbbz={lbbz}, hpbl = {hpbl}
                where dti={dti}
            """
        db.update(usql)


def updateFbCje(dti):
    db = SqliteUtil.get_instance(dbConfig=config)
    fbcjesql = f"select dti, code, count, cje, type  from stock_board where dti={dti}"
    fb = db.get_one(fbcjesql)
    ztcje = 0
    dtcje = 0
    lbcje = 0
    lb2cje = 0
    lb3cje = 0
    lb4pcje = 0
    if fb is not None:
        count = fb[2]
        cje = fb[3]
        type = fb[4]
        if type == 0:
            dtcje = dtcje + cje
        elif count == 1:
            ztcje = ztcje + cje
        elif count == 2:
            ztcje = ztcje + cje
            lbcje = lbcje + cje
            lb2cje = lb2cje + cje
        elif count == 3:
            ztcje = ztcje + cje
            lbcje = lbcje + cje
            lb3cje = lb3cje + cje
        else:
            ztcje = ztcje + cje
            lbcje = lbcje + cje
            lb4pcje = lb4pcje + cje
    usql = f"""
            update market_sentiment set 
                 ztcje={ztcje}, dtcje={dtcje}, lbcje={lbcje}, lb2cje={lb2cje}, lb3cje={lb3cje}, lb4pcje={lb4pcje}
            where dti={dti}
        """
    db.update(usql)


def updateLbbl(dti):
    db = SqliteUtil.get_instance(dbConfig=config)
    sql = f"select dti, lbs from market_sentiment where dti = {dti}"
    lb = db.get_one(sql)
    lbs = lb[1]

    zsql = f"select dti, lbs from market_sentiment where dti < {dti} order by dti desc limit 1"
    zlb = db.get_one(zsql)
    zlbs = zlb[1]

    lbbz = round(lbs/zlbs, 2)

    usql = f"""
            update market_sentiment set lbbz={lbbz}
            where dti={dti}
        """
    db.update(usql)


def updateDnSn(dti):
    db = SqliteUtil.get_instance(dbConfig=config)
    sql = f"""
        select
            ms.dti
            ,ms.hpbl
            ,ms.zts
            ,ms.lbs
            ,ms.d5s
            ,ms.zsbzbl
            ,ms.zsbddbl
            ,ms.zlbzbl
            ,ms.zlbddbl
            ,ms.lbbz
            ,ms.bzlbdbl
        from market_sentiment ms
        where dti={dti}
        """
    sentiment = db.get_one(sql)
    dn, sn = 0, 0
    hpbl = sentiment[1]
    zts = sentiment[2]
    lbs = sentiment[3]
    d5s = sentiment[4]
    zsbzbl = sentiment[5]
    zsbddbl = sentiment[6]
    zlbzbl = sentiment[7]
    zlbddbl = sentiment[8]
    lbbz = sentiment[9]
    bzlbdbl = sentiment[10]

    sn = sn + 2 if zts >= 40 else sn - 2
    sn = sn + 2 if lbs >= 10 else sn - 2
    sn = sn + 2 if d5s < 100 else sn - 2
    sn = sn + 2 if hpbl >= 60 else sn - 2
    sn = sn + 2 if d5s*1.0/zts < 2 else sn - 2

    dn = dn + 2 if zsbzbl >= 60 else dn - 2
    dn = dn + 2 if zsbddbl < 30 else dn - 2
    dn = dn + 2 if zlbzbl >= 60 else dn - 2
    dn = dn + 2 if zlbddbl < 30 else dn - 2
    dn = dn + 2 if lbbz >= 60 else dn - 2
    dn = dn + 2 if bzlbdbl < 50 else dn - 2

    usql = f"""
                update market_sentiment set sn={sn}, dn={dn}
                where dti={dti}
            """
    db.update(usql)


def updateZZT(zdti, dti):
    db = SqliteUtil.get_instance(dbConfig=config)
    bsql = f"""
            select b.dti, b.code, b.type, b.count, b.cje, round(m.zf_open, 2), round(m.zf_close, 2) 
            from stock_board b left join stock_move m on b.code = m.code and b.tdti = m.dti
            where b.dti={zdti}
        """
    ball = db.get_all(bsql)
    if ball is None or len(ball) == 0:
        return
    zsbs = 0
    zlbs = 0
    bzlbs = 0
    dlbgs = []

    zztzs = 0
    zztds = 0
    zztdzs = 0
    zztdds = 0

    zsbzs = 0
    zsbds = 0
    zsbdzs = 0
    zsbdds = 0
    zsboc5ds = 0

    zlboc5ds = 0
    zlbzs = 0
    zlbds = 0
    zlbdzs = 0
    zlbdds = 0

    z2lbzs = 0
    z2lbds = 0
    z2lbdzs = 0
    z2lbdds = 0

    z3lbzs = 0
    z3lbds = 0
    z3lbdzs = 0
    z3lbdds = 0

    z4plbzs = 0
    z4plbds = 0
    z4plbdzs = 0
    z4plbdds = 0

    ztcje = 0
    dtcje = 0
    lbcje = 0
    lb2cje = 0
    lb3cje = 0
    lb4pcje = 0

    for b in ball:
        code = b[1]
        type = b[2]
        count = b[3]
        cje = b[4]
        topenzf = b[5]
        tclosezf = b[6]
        if topenzf is None or tclosezf is None:
            continue
        if type == 0:
            dtcje = dtcje + cje
        else:
            ztcje = ztcje + cje
            if tclosezf > 0:
                zztzs = zztzs + 1
            elif tclosezf < 0:
                zztds = zztds + 1
            if tclosezf >= 5:
                zztdzs = zztdzs + 1
            elif tclosezf < -5:
                zztdds = zztdds + 1
            if count == 1:
                zsbs = zsbs + 1
                if tclosezf > 0:
                    zsbzs = zsbzs + 1
                elif tclosezf < 0:
                    zsbds = zsbds + 1
                if tclosezf >= 5:
                    zsbdzs = zsbdzs + 1
                elif tclosezf < -5:
                    zsbdds = zsbdds + 1

                if topenzf - tclosezf >= 5:
                    zsboc5ds = zsboc5ds + 1
            else:
                if tclosezf <= 9:
                    bzlbs = bzlbs + 1
                else:
                    dlbgs.append(code)
                zlbs = zlbs + 1
                lbcje = lbcje + cje
                if tclosezf > 0:
                    zlbzs = zlbzs + 1
                elif tclosezf < 0:
                    zlbds = zlbds + 1
                if tclosezf >= 5:
                    zlbdzs = zlbdzs + 1
                elif tclosezf < -5:
                    zlbdds = zlbdds + 1
                if topenzf - tclosezf >= 5:
                    zlboc5ds = zlboc5ds + 1
                if count == 2:
                    lb2cje = lb2cje + cje
                    if tclosezf > 0:
                        z2lbzs = z2lbzs + 1
                    elif tclosezf < 0:
                        z2lbds = z2lbds + 1
                    if tclosezf >= 5:
                        z2lbdzs = z2lbdzs + 1
                    elif tclosezf < -5:
                        z2lbdds = z2lbdds + 1
                elif count == 3:
                    lb3cje = lb3cje + cje
                    if tclosezf > 0:
                        z3lbzs = z3lbzs + 1
                    elif tclosezf < 0:
                        z3lbds = z3lbds + 1
                    if tclosezf >= 5:
                        z3lbdzs = z3lbdzs + 1
                    elif tclosezf < -5:
                        z3lbdds = z3lbdds + 1
                else:
                    lb4pcje = lb4pcje + cje
                    if tclosezf > 0:
                        z4plbzs = z4plbzs + 1
                    elif tclosezf < 0:
                        z4plbds = z4plbds + 1
                    if tclosezf >= 5:
                        z4plbdzs = z4plbdzs + 1
                    elif tclosezf < -5:
                        z4plbdds = z4plbdds + 1
    jbsql = f"""
            select b.dti, b.code, b.type, b.count, b.cje, round(m.zf_open, 2), round(m.zf_close, 2) 
            from stock_board b left join stock_move m on b.code = m.code and b.tdti = m.dti
            where b.dti={zdti} and b.code in {','.join(dlbgs)}
        """
    jball = db.get_all(bsql)
    if jball is not None:
        jball = []
    bzlbs = bzlbs + len(dlbgs) - len(jball)
    bzlbdbl = round(1.0*zlbds/bzlbs*100, 2)
    usql = f"""
            update market_sentiment set 
                zsbs = {zsbs}, zlbs = {zlbs}, zztzs = {zztzs}, zztds = {zztds}, zztdzs = {zztdzs}, zztdds = {zztdds}, 
                zsbzs = {zsbzs}, zsbds = {zsbds}, zsbdzs = {zsbdzs}, zsbdds = {zsbdds}, zsboc5ds = {zsboc5ds}, 
                zlboc5ds = {zlboc5ds}, zlbzs = {zlbzs}, zlbds = {zlbds}, zlbdzs = {zlbdzs}, zlbdds = {zlbdds}, 
                z2lbzs = {z2lbzs}, z2lbds = {z2lbds}, z2lbdzs = {z2lbdzs}, z2lbdds = {z2lbdds}, 
                z3lbzs = {z3lbzs}, z3lbds = {z3lbds}, z3lbdzs = {z3lbdzs}, z3lbdds = {z3lbdds}, 
                z4plbzs = {z4plbzs}, z4plbds = {z4plbds}, z4plbdzs = {z4plbdzs}, z4plbdds = {z4plbdds}, 
                ztcje = {ztcje}, dtcje = {dtcje}, lbcje = {lbcje}, lb2cje = {lb2cje}, lb3cje = {lb3cje}, lb4pcje = {lb4pcje},
                bzlbdbl ={bzlbdbl}
            where dti={dti}
        """
    db.update(usql)

def updateZT(dti):
    db = SqliteUtil.get_instance(dbConfig=config)
    bsql = f"""
            select dti, code, type, count, cje
            from stock_board where dti={dti}
        """
    ball = db.get_all(bsql)
    if ball is None or len(ball) == 0:
        return
    zts = 0
    dts = 0
    lbs = 0
    lbs2 = 0
    lbs3 = 0
    lbs4p = 0
    ztcje = 0
    dtcje = 0
    lbcje = 0
    lb2cje = 0
    lb3cje = 0
    lb4pcje = 0
    for b in ball:
        type = b[2]
        count = b[3]
        cje = b[4]
        if type == 0:
            dts = dts + 1
            dtcje = dtcje + cje
        else:
            zts = zts + 1
            ztcje = ztcje + cje
            if count >= 2:
                lbs = lbs + 1
                lbcje = lbcje + cje
                if count == 2:
                    lbs2 = lbs2 + 1
                    lb2cje = lb2cje + cje
                elif count == 3:
                    lbs3 = lbs3 + 1
                    lb3cje = lb3cje + cje
                else:
                    lbs4p = lbs4p + 1
                    lb4pcje = lb4pcje + cje
    ssql = f"select dti from market_sentiment where dti={dti}"
    ms = db.get_one(ssql)
    if ms is None:
        isql = f"insert into market_sentiment(dti) values ({dti})"
        db.save(isql)

    usql = f"""
        update market_sentiment set 
            zts = {zts}, dts = {dts}, lbs = {lbs}, lbs2 = {lbs2}, lbs3 = {lbs3}, lbs4p = {lbs4p}, 
            ztcje = {ztcje}, dtcje = {dtcje}, lbcje = {lbcje}, lb2cje = {lb2cje}, lb3cje = {lb3cje}, lb4pcje = {lb4pcje}
        where dti={dti}
    """
    db.update(usql)


def updateKJB(dti):
    db = SqliteUtil.get_instance(dbConfig=config)
    bsql = f"""
            select max(count) 
            from stock_board where dti={dti} and type=1 limit 1
        """
    kjbR = db.get_one(bsql)
    if kjbR is None or len(kjbR) == 0:
        return
    kjb = kjbR[0]
    msUsql = f"update market_sentiment set kjb={kjb} where dti={dti}"
    db.update(msUsql)


def initMarketSentiment(ms: dict=None) -> bool:
    db = SqliteUtil.get_instance(dbConfig=config)
    dtiR = db.get_one(f"select dti from market_sentiment where dti={ms['dti']}")
    if dtiR is None:
        db.save(f"""
            insert into market_sentiment(dti)
            values ({ms['dti']})
        """)


def insertIndexData(dti: int, qdt: str):
    logger.info(f"{dti}的指数数据开始下载")
    res = pywencai.get(query=f'{qdt}涨幅、成交额', sort_key='股票代码', sort_order='asc', query_type='zhishu', loop=True)
    if res is None:
        logger.warning("获取指数数据失败，重新尝试")
        res = pywencai.get(query=f'{qdt}涨幅、成交额', sort_key='股票代码', sort_order='asc', query_type='zhishu',
                           loop=True)
    if res is None:
        logger.error("获取指数数据失败")
        raise RuntimeError("获取指数数据失败")
    logger.info(f"{dti}的指数数据下载成功")
    yi = 10**8
    shDF = res.loc[res['指数简称']=='上证指数'].iloc[0]
    shzf = float(shDF[f'指数@涨跌幅:前复权[{dti}]'])
    shcje = round(float(shDF[f'指数@成交额[{dti}]'])/yi, 2)

    szDF = res.loc[res['指数简称']=='深证成指'].iloc[0]
    szzf = float(szDF[f'指数@涨跌幅:前复权[{dti}]'])
    szcje = round(float(szDF[f'指数@成交额[{dti}]'])/yi, 2)

    cyDF = res.loc[res['指数简称']=='创业板指'].iloc[0]
    cyzf = float(cyDF[f'指数@涨跌幅:前复权[{dti}]'])
    cycje = round(float(cyDF[f'指数@成交额[{dti}]'])/yi, 2)

    kcDF = res.loc[res['指数简称'] == '科创50'].iloc[0]
    kczf = float(kcDF[f'指数@涨跌幅:前复权[{dti}]'])
    kccje = round(float(kcDF[f'指数@成交额[{dti}]'])/yi, 2)

    bjDF = res.loc[res['指数简称']=='北证50'].iloc[0]
    bjzf = float(bjDF[f'指数@涨跌幅:前复权[{dti}]'])
    bjcje = round(float(bjDF[f'指数@成交额[{dti}]'])/yi, 2)


    zfstztbxDF = res.loc[res['指数简称']=='昨日非ST涨停表现'].iloc[0]
    zfstztbx = float(zfstztbxDF[f'指数@涨跌幅:前复权[{dti}]'])
    zsbfstbxDF = res.loc[res['指数简称']=='昨日ST首板股表现'].iloc[0]
    zsbfstbx = float(zsbfstbxDF[f'指数@涨跌幅:前复权[{dti}]'])
    if zsbfstbx is None or math.isnan(zsbfstbx):
        zsbfstbx = 0
    zlbfstbxDF = res.loc[res['指数简称']=='昨日非ST连板'].iloc[0]
    zlbfstbx = float(zlbfstbxDF[f'指数@涨跌幅:前复权[{dti}]'])
    z2lbfstbxDF = res.loc[res['指数简称']=='昨日非ST二板表现'].iloc[0]
    z2lbfstbx = float(z2lbfstbxDF[f'指数@涨跌幅:前复权[{dti}]'])
    z3lbfst = res.loc[res['指数简称'] == '昨日非ST三板表现']
    z3lbfstbx = 0
    if z3lbfst is not None and not z3lbfst.empty:
        z3lbfstbx = float(z3lbfst.iloc[0][f'指数@涨跌幅:前复权[{dti}]'])
    if z3lbfstbx is None or math.isnan(z3lbfstbx):
        z3lbfstbx = 0
    z4plbfst = res.loc[res['指数简称']=='昨日非ST三板以上表现']
    z4plbfstbx = 0
    if z4plbfst is not None and not z4plbfst.empty:
        z4plbfstbx = float(z4plbfst.iloc[0][f'指数@涨跌幅:前复权[{dti}]'])
    if z4plbfstbx is None or math.isnan(z4plbfstbx):
        z4plbfstbx = 0
    db = SqliteUtil.get_instance(dbConfig=config)
    db.save(f"update market_sentiment set shzf = {shzf}, bjzf = {bjzf}, cyzf = {cyzf}, szzf = {szzf}, kczf = {kczf}, zfstztbx = {zfstztbx}, zsbfstbx = {zsbfstbx}, z4plbfstbx = {z4plbfstbx}, z3lbfstbx = {z3lbfstbx}, zlbfstbx = {zlbfstbx}, z2lbfstbx = {z2lbfstbx}, shcje={shcje}, szcje={szcje}, cycje={cycje}, kccje={kccje}, bjcje={bjcje} where dti={dti}")
    logger.info(f"{dti}的指数数据插入成功")


def insertOtherData(dti: int, qdt: str):
    logger.info(f"{dti}的其他数据开始下载")
    def getCount(query) -> int:
        logger.info(f"{query}数据开始下载")
        res = pywencai.getRowCount(query=f'{query}')
        if res is None:
            logger.warning(f"获取{query}失败，重新尝试")
            res = pywencai.get(query=f'{query}')
        if res is None:
            logger.error(f"获取{query}失败")
            raise RuntimeError(f"获取{query}失败")
        logger.info(f"{query}下载成功")
        return res

    hps = getCount(f"{qdt}涨幅大于0的股票")
    lps = getCount(f"{qdt}跌幅大于0的股票")
    zbs = getCount(f"{qdt}炸板非ST非新股非退市股")
    z5s = getCount(f"{qdt}涨幅大于5非st非新股非退市股")
    d5s = getCount(f"{qdt}跌幅大于5非st非新股非退市股")
    db = SqliteUtil.get_instance(dbConfig=config)
    db.save(
        f"update market_sentiment set hps={hps}, lps={lps}, zbs={zbs}, z5s={z5s}, d5s={d5s} where dti={dti}")
    logger.info(f"{dti}的其他数据插入成功")


def deleteMarketSentiment(dti):
    db = SqliteUtil.get_instance(dbConfig=config)
    dtiR = db.delete(f"delete from market_sentiment where dti={dti}")
    logger.info(f"删除{dti}的股票行情汇总信息成功")


def marketSentiment(ms: dict=None):
    db = SqliteUtil.get_instance(dbConfig=config)
    if ms is None or 'dti' not in ms:
        dti = getTodayyyyymmddInt()
        if ms is None:
            ms = dict()
        ms['dti'] = dti
    else:
        dti = ms['dti']
    logger.info(f"开始更新{dti}的股票行情汇总信息")
    # initMarketSentiment(ms)
    qdt = f"{str(dti)[4:6]}月{str(dti)[6:]}日"
    insertIndexData(dti, qdt)
    insertOtherData(dti, qdt)
    zsql = f"""
                select dti from market_sentiment
                where dti < {dti} order by dti desc limit 1
            """
    zr = db.get_one(zsql)
    zdti = zr[0]
    updateZT(dti)
    updateZZT(zdti, dti)
    updateRatios(dti)
    updateDnSn(dti)
    updateKJB(dti)
    logger.info(f"完成更新{dti}的股票行情汇总信息")


if __name__ == "__main__":
    marketSentiment()

